<template>
  <div class="home">
    <!-- 面包屑 -->
    <mbx name1="商品管理" name2="添加商品信息"></mbx>
    <!-- 卡片区 -->
    <el-card class="mt16">
      <!-- 警告 -->
      <el-alert title="消息提示的文案" type="info" show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="active * 1"
        finish-status="success"
        class="mt16"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单验证 -->
      <el-form
        :model="form"
        :rules="rules"
        ref="add"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- tabs页 -->
        <el-tabs
          tab-position="left"
          v-model="active"
          class="mt16"
          :before-leave="beforeLeave"
          @tab-click="next"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="form.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="form.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="form.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="form.goods_cat"
                :options="options"
                :props="{
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  children: 'children',
                }"
                @change="handleChange"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form v-for="(item, index) in dong" :key="index">
              <el-form-item :label="item.attr_name">
                <el-checkbox-group
                  v-model="item.attr_vals"
                  v-for="(ite, ind) in item.attr_vals"
                  :key="ind"
                >
                  <el-checkbox :label="ite" />
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态参数 -->
            <el-form>
              <el-form-item
                v-for="(item, index) in jing"
                :key="index"
                :label="item.attr_name"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-remove="handleRemove"
              :on-success="success"
              :headers="headers"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <QuillEditor theme="snow" v-model="form.goods_introduce" />
            <el-button type="primary" class="mt16" @click="addlist"
              >添加</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getcate, getcanshulist, addgoods } from "../http/api.js";
import { useRouter } from "vue-router";
export default {
  setup(props) {
    const router = useRouter();
    const add = ref(null);
    const obj = reactive({
      active: "0",
      form: {
        goods_name: "",
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      rules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: "blur",
          },
        ],
      },
      options: [], //存放三级联动数据的数组
      jing: [], //存放静态参数的数组
      dong: [], //存放动态参数的数组
      headers: { Authorization: sessionStorage.getItem("token") },
    });
    onMounted(() => {
      getlist();
    });
    // 标签离开的函数
    const beforeLeave = (newo, oldl) => {
      if (oldl == "0" && obj.form.goods_cat.length !== 3) {
        ElMessage.error("请选择商品分类哦!");
        return false;
      }
    };
    // 三级联动的改变事件
    const handleChange = () => {
      if (obj.form.goods_cat.length !== 3) {
        obj.form.goods_cat = [];
      }
    };
    // 三级联动的数据
    const getlist = async () => {
      const res = await getcate();
      console.log("这是添加商品的三级联动", res);
      obj.options = res;
    };
    // tab 被选中时触发的方法
    const next = async () => {
      if (obj.active == "1") {
        const res = await getcanshulist(js.value);
        console.log("动态参数", res);
        res.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });
        obj.dong = res;
      }
      //   静态参数
      if (obj.active == "2") {
        const res = await getcanshulist(js.value, "many");
        console.log("静态参数", res);
        obj.jing = res;
      }
    };
    // 计算属性 获取分类的id
    const js = computed(() => {
      return obj.form.goods_cat[obj.form.goods_cat.length - 1];
      console.log(
        "分类id",
        obj.form.goods_cat[obj.form.goods_cat.length - 1].value
      );
    });
    // 删除图片
    const handleRemove = (val) => {
      console.log("删除的图片", val);
      const index = obj.form.pics.findIndex((item) => {
        return item.pic == val.response.data.tmp_path;
      });
      obj.form.pics.splice(index, 1);
      console.log("删除成功的数组", obj.form.pics);
    };
    // 添加图片
    const success = (val) => {
      console.log("上传成功的图片", val);
      obj.form.pics.push({ pic: val.data.tmp_path });
      console.log("上传成功的数组", obj.form.pics);
    };
    // 添加到列表
    const addlist = () => {
      add.value.validate(async (valid) => {
        if (valid) {
          //   将三级联动的数据改为字符串
          obj.form.goods_cat = obj.form.goods_cat.join(",");
          //   将静态数据和动态数据结合一下
          const j = obj.jing.map((item) => {
            // console.log("jing", item.attr_vals);
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
          });
          const d = obj.dong.map((item) => {
            return {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
          });
          obj.form.attrs = [...j, ...d];
          const res = await addgoods(obj.form);
          ElMessage.success("请选择商品分类哦!");
          router.push("/goods");
        } else {
          ElMessage.error("您还有商品未填写完整哦!");
          console.log("error submit!!");
          return false;
        }
      });
    };
    return {
      ...toRefs(obj),
      beforeLeave,
      handleChange,
      next,
      handleRemove,
      success,
      addlist,
      add,
    };
  },
};
</script>
<style lang="scss" scoped>
.home {
  width: 100%;
  ::v-deep .el-step__title {
    font-size: 14px;
  }
  ::v-deep .ql-editor {
    height: 300px;
  }
}
</style>
